
using System;

namespace raycsharp
{
	public class Sphere : SceneObject {
		private double radius { get; set; }
		private Vector center { get; set; }
		public Sphere(double _radius, Vector _center, 
		              Color _ambient, Color _diffuse, Color _specular) : base(_ambient, _diffuse, _specular) {
			radius = _radius;
			center = _center;
		}
		
		public override Vector get_normal (Vector point)
		{
			return point.sub_vect(center).normalize();	
		}
		
		public override IntersectionResult intersection (Ray _ray)
		{
			/* AxÂ² + Bx + C = 0 */
			
			Vector intersection_point = new Vector();
		    
			double delta,distance=0.0;
			double a = 1.0;
			double b = 2.0*(_ray.direction.dot_product(_ray.origin) - _ray.direction.dot_product(center));
			double c = Math.Abs(_ray.origin.dot_product(_ray.origin) - 2.0*_ray.origin.dot_product(center) + center.dot_product(center)) - radius*radius;
			delta = b*b - 4.0*a*c;
			if (delta >= 0.0) {
				double raiz2 = (-b - Math.Sqrt(delta))/2.0*a;
				if(raiz2 < 0.0) raiz2 = 0.0;
				else distance = raiz2;
				if(distance >= 0.0) {
					intersection_point = _ray.origin + _ray.direction*distance;
					return new IntersectionResult(this,intersection_point, distance, true);
				}
			}
			return new IntersectionResult(this,intersection_point,distance,false);
		}
	}
}
